﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace COC.Graphics
{
	class TerrainComponent : IRenderComponent
	{
		Effect m_TerrainEffect;
		VertexDeclaration m_VDecl;

		public TerrainComponent()
		{
		}

		public override void Initialize()
		{
			m_TerrainEffect = CoCGame.Singleton.Content.Load<Effect>(@"Shaders\Terrain");
			VertexElement[] elements = new VertexElement[] {
				new VertexElement(0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0),
				new VertexElement(1, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Normal, 0),
				new VertexElement(2, 0, VertexElementFormat.Vector2, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0),
			};
			m_VDecl = new VertexDeclaration(CoCGame.Singleton.GraphicsDevice, elements);
		}

		public override void Render()
		{
			CoCGame.Singleton.GraphicsDevice.VertexDeclaration = m_VDecl;

			m_TerrainEffect.Parameters["World"].SetValue(Matrix.Identity);
			m_TerrainEffect.Parameters["View"].SetValue(CoCGame.Singleton.GameCamera.MatView);
			m_TerrainEffect.Parameters["Projection"].SetValue(CoCGame.Singleton.GameCamera.MatProj);
			m_TerrainEffect.Parameters["LightDir"].SetValue(Vector3.Normalize(new Vector3(-1, -1, -1)));
			m_TerrainEffect.Parameters["CameraPos"].SetValue(CoCGame.Singleton.GameCamera.Position);
			m_TerrainEffect.Parameters["DiffuseLight"].SetValue(new Vector3(1.0f, 1.0f, 1.0f));
			m_TerrainEffect.Parameters["SpecularLight"].SetValue(new Vector3(1.0f, 1.0f, 1.0f));
			m_TerrainEffect.Parameters["AmbientLight"].SetValue(new Vector3(0.3f, 0.3f, 0.3f));
			m_TerrainEffect.Parameters["SpecularPower"].SetValue(10.0f);

			m_TerrainEffect.Parameters["DiffuseTexture"].SetValue(TerrainManager.Singleton.m_BaseTexture[0]);
			
			m_TerrainEffect.Begin();
			foreach (EffectPass pass in m_TerrainEffect.CurrentTechnique.Passes)
			{
				pass.Begin();
				TerrainManager.Singleton.RootTile.Render();
				pass.End();
			}
			m_TerrainEffect.End();
		}

		public override void Dispose()
		{
			if (m_TerrainEffect != null)
			{
				m_TerrainEffect.Dispose();
				m_TerrainEffect = null;
			}
			if (m_VDecl != null)
			{
				m_VDecl.Dispose();
				m_VDecl = null;
			}
		}
	}
}